package com.carskeeper.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.carskeeper.common.dtos.AppHttpCodeEnum;
import com.carskeeper.common.dtos.PageResponseResult;
import com.carskeeper.common.dtos.ResponseResult;
import com.carskeeper.common.exception.AcException;
import com.carskeeper.excel.CustomHandler;
import com.carskeeper.model.body.dtos.QueryOwnerDto;
import com.carskeeper.model.body.dtos.UpdateStatusDto;
import com.carskeeper.model.body.pojos.BodyCarOwner;
import com.carskeeper.body.service.BodyCarOwnerService;
import com.carskeeper.mapper.BodyCarOwnerMapper;
import com.carskeeper.model.body.vo.BodyCarOwnerVo;
import com.carskeeper.model.body.vo.BodyOwnerExcel;
import com.carskeeper.utils.common.BeanHelper;
import com.fasterxml.jackson.core.util.ByteArrayBuilder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.mapstruct.Context;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.xmlunit.util.Convert;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Component
public class BodyCarOwnerServiceImpl implements BodyCarOwnerService {

    @Autowired
    private BodyCarOwnerMapper bodyCarOwnerMapper;


    @Override
    public PageResponseResult<List<BodyCarOwnerVo>> findOwnerByPage(QueryOwnerDto dto) {
        //参数初始化
        if (dto.getPage()==null)dto.setPage(1);
        if (dto.getPageSize()==null)dto.setPageSize(10);
        //进行查询
        PageHelper.startPage(dto.getPage(), dto.getPageSize(),true);
        List<BodyCarOwner> bodyCarOwnerList =  bodyCarOwnerMapper.findByPage(dto);
        PageInfo<BodyCarOwner> pageInfo = new PageInfo<>(bodyCarOwnerList);
        //结果包装
        PageResponseResult<List<BodyCarOwnerVo>> result = new PageResponseResult<>(pageInfo.getPageNum(),pageInfo.getPageSize(),Integer.parseInt(String.valueOf(pageInfo.getTotal())));
        List<BodyCarOwnerVo> bodyCarOwnerVos = BeanHelper.copyWithCollection(bodyCarOwnerList, BodyCarOwnerVo.class);
        result.setData(bodyCarOwnerVos);
        return result;
    }

    @Override
    public ResponseResult updateOwnerStatus(UpdateStatusDto dto) {
        //参数校验
        if (dto.getOwnerId()==null||dto.getStatus()==null){
            throw new AcException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //修改数据库
        bodyCarOwnerMapper.updateOwnerStatus(dto);
        return ResponseResult.okResult(null);
    }

    @Override
    public String exportOwner(QueryOwnerDto dto) throws IOException {
        //参数初始化
        if (dto.getPage()==null)dto.setPage(1);
        if (dto.getPageSize()==null)dto.setPageSize(10);
        //获取列表信息
        List<BodyCarOwnerVo> carOwnerVos = this.findOwnerByPage(dto).getData();
        //数据类型转换
        int number = 0;
        ArrayList<BodyOwnerExcel> bodyOwnerExcels = new ArrayList<>();
        for (BodyCarOwnerVo carOwnerVo : carOwnerVos) {
            BodyOwnerExcel bodyOwnerExcel = new BodyOwnerExcel(number++, carOwnerVo.getName(), carOwnerVo.getPhone(), carOwnerVo.getStatus());
            bodyOwnerExcels.add(bodyOwnerExcel);
        }
        String foldername = "D:" + File.separator + "员工数据" + File.separator + "2022";
        File folder = new File(foldername);

        // 4.2 如果文件夹不存在，创建文件夹
        if(!folder.exists()){
            folder.mkdirs();
        }

        // 4.3 指定文件名，D:/考勤数据/xxx公司-2021-11-考勤数据.xls
        String filename = foldername + File.separator +  "员工数据.xls";
        File file = new File(filename);
        //通过response获取输出流, 并生成的Excel输出
        EasyExcel.write(file)
                .excelType(ExcelTypeEnum.XLS)
                .head(this.handleHeaders())
                .registerWriteHandler(this.horizontalCellStyleStrategy())
                .registerWriteHandler(new CustomHandler())
                .sheet("车主信息")
                .doWrite(this.handleData(bodyOwnerExcels));


        StringBuffer buffer = new StringBuffer();
        BufferedReader bf= new BufferedReader(new FileReader(filename));
        String s = null;
        while((s = bf.readLine())!=null){//使用readLine方法，一次读一行
            buffer.append(s.trim());
        }

        return filename;
    }

    /**
     * 处理每行数据
     * @param bodyOwnerExcels
     * @return
     */
    private List<List<String>> handleData(ArrayList<BodyOwnerExcel> bodyOwnerExcels) {
        List<List<String>> dataList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(bodyOwnerExcels)) {
            for (BodyOwnerExcel bodyOwnerExcel : bodyOwnerExcels) {
                // 每一行基本信息
                List<String> rowData = new ArrayList<>();
                rowData.add(String.valueOf(bodyOwnerExcel.getNumber())); // 序号
                rowData.add(bodyOwnerExcel.getName()); // 姓名
                rowData.add(bodyOwnerExcel.getPhone()); // 手机号
                rowData.add(bodyOwnerExcel.getStatus()?"锁定":"正常"); // 状态
                // 将每行数据添加到data中
                dataList.add(rowData);
            }
        }
        return dataList;
    }


    /**
     * 处理表头
     * @return
     */
    private List<List<String>> handleHeaders() {
        List<List<String>> headers = new ArrayList<>();
        headers.add(Arrays.asList("序号"));
        headers.add(Arrays.asList("车主名称"));
        headers.add(Arrays.asList("车主手机号"));
        headers.add(Arrays.asList("是否锁定"));
        return headers;
    }

    /**
     * 设置样式
     */
    public HorizontalCellStyleStrategy horizontalCellStyleStrategy() {

        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //内容策略 - 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        //设置字体
        WriteFont font = new WriteFont();
        font.setFontName("阿里巴巴普惠体");
        font.setFontHeightInPoints((short) 11);
        contentWriteCellStyle.setWriteFont(font);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(contentWriteCellStyle, contentWriteCellStyle);

        return horizontalCellStyleStrategy;
    }
}
